package com.tuling.code.algorithm.loadbalance.simple;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 加权轮询（Weight Round Robin）法
 * @author javaw
 */
public class WeightRoundRobin implements LoadBlanceStragety {
	
	//server下标
	private static Integer pos = 0;

	@Override
	public String getServer(String src) {
		// 重建一个Map，避免服务器的上下线导致的并发问题
		Map<String, Integer> serverMap = new HashMap<>();
		serverMap.putAll(IpMap.serverWeightMap);

		// 获取IP地址列表
		Iterator<String> it = serverMap.keySet().iterator();
		
		List<String> serverList = new ArrayList<>();

		//根据权重重新构建serverlist
		while(it.hasNext()){
			String server = it.next();
			int weight = serverMap.get(server);
			for(int i = 0; i < weight ; i++){
				serverList.add(server);
			}
		}
		
		String server = null;
		
		synchronized (pos) {
			if(pos >= serverList.size()){
				pos = 0;
			}
			
			server = serverList.get(pos);
			pos ++;
		}
		System.out.println("serverPos="+ pos + " , weight = "+ serverMap.get(server) + " , serverIp = " + server);
		return server;
	}

}
